<template>
    <div>
        <!-- <TopSelect></TopSelect> -->
        <!-- <buildTag :show-action="isAction"></buildTag> -->

        <div class="card">
            <tabs
                v-model:active="active" line-width="20px" line-height="4px" title-active-color="#333"
                title-inactive-color="#848484"
            >
                <tab title="自定义标签" name="customTag">
                    <div class="custom-tag">
                        <div class="tag">
                            <div class="title">
                                您要投放的城市
                            </div>
                            <tags-list
                                :data="cityData" :selection-data="formCity.selectCity"
                                @click="handleClick"
                            ></tags-list>
                            <div class="city-label">
                                已选：
                                <span class="city-sel">{{ citytxt }}</span>
                            </div>
                            <div class="title">
                                您的目标人群标签
                            </div>
                            <template v-for="(item, index) in personList" :key="index">
                                <tags-list
                                    :title="item.name" :is-multiple="true" :show-limit="true" :data="item.children"
                                    label="name" value="id" :selection-data="form[index]"
                                    @click="handleClick($event, index)"
                                />
                            </template>
                            <div class="title-sm">
                                消费偏好
                            </div>
                            <MyCell
                                label="选择偏好" placeholder="请选择" :value="preference" :show-bottom-line="false"
                                @click="pickTime"
                            ></MyCell>
                        </div>
                    </div>
                </tab>
                <tab title="新潮精选人群" name="carefullyTag">
                    <div class="person-list">
                        <div
                            v-for="(item, index) in personTagList" :key="index" class="person-item"
                            :class="currentCheckTagArrId.includes(item.id) ? 'on' : ''" @click="onCheckPerson(item)"
                        >
                            <img :src="getImageUrl(`person-icon${index + 1}@2x.png`)" />
                            <div class="person-detail">
                                <h4>{{ item.name }}</h4>
                                <p>{{ item.mark }}</p>
                            </div>
                            <img
                                v-if="currentCheckTagArrId.includes(item.id)" src="./../../../assets/img/勾选@2x.png"
                                class="check"
                            />
                        </div>
                    </div>
                </tab>
            </tabs>
        </div>


        <footer class="footer">
            <Button type="primary" block @click="next">
                下一步
            </Button>
            <div class="van-safe-area-bottom"></div>
        </footer>
        <city-area-selecter
            :show="showCityPicker" :list="cityList" :type="selecterType" :selected="checkedData"
            :is-require="false" @close="showCityPicker = false" @confirm="onCityConfirm"
        />
    </div>
</template>


<script name="selectByTag" lang="ts" setup>
import { ref, reactive, onMounted, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { Button, Tab, Tabs, Toast } from 'vant';
import { City } from './consts';
import tagsList from '@/components/tagsList.vue';
import CityAreaSelecter from '@/components/CityAreaSelecter/index.vue';
// import TopSelect from '@/components/TopSelect/index.vue';
// import buildTag from '@/components/buildTag/index.vue';
import { getTopTags, getChildTags } from '@/api/selectByTag';
import { TreeChildModel, formDataModel } from '../../selectByTag/selectByTag.module';
import { ReturnData } from '@/components/CityAreaSelecter/city.module';
import { getImageUrl } from '@/utils';
import { store } from '@/store';
import MyCell from '@/components/MyCell/index.vue';


const router = useRouter();
const currentCheckTag = ref<TreeChildModel[]>([]);
const cityData = City;
const showCityPicker = ref<boolean>(false);
const preference = ref('');
const selecterType = ref(1);
const personList = ref<TreeChildModel[]>([]);
const personTagList = ref<TreeChildModel[]>([]);
const active = ref('customTag');
const formData = reactive<formDataModel>({
    city: [],
    cityCodeList: [],
    preference: [],
    preferenceIdList: [],
    isNationwide: false,
    customTag: [],
    customKeyTag: {},
    checkedCityData: [],
    checkedPreferenceData: [],
    currentCheckObjTag: []
});
const cityList = ref<TreeChildModel[]>([]);
interface Tag {
    [key: string]: string | number,
}
interface Form {
    [key: string]: Tag[]
}
const form = reactive<Form>({

});
const formCity = reactive<Form>({
    selectCity: [
        {
            label: '按省市',
            value: '1',
        }
    ],
});
const tidArr = ref<string[]>([]);
const provinceList = ref<TreeChildModel[]>([]);
const cityLevelList = ref<TreeChildModel[]>([]);
const industryList = ref<TreeChildModel[]>([]);
const checkedData = ref<TreeChildModel[]>([]);
const cityAllList = ref<TreeChildModel[]>([]);
const citytxt = ref('');
onMounted(async () => {
    const tagsList = await getTopTags() as unknown as TreeChildModel[];
    tidArr.value = tagsList.map((item: TreeChildModel) => item.id);
    personList.value = await getChildTags(1);
    personTagList.value = await getChildTags(4);
    provinceList.value = await getChildTags(3);
    cityLevelList.value = await getChildTags(5);
    industryList.value = await getChildTags(2);
    const city = store.state.app.home?.selectCity as unknown as TreeChildModel;
    const cityList = provinceList.value.map((item: TreeChildModel) => item.children);
    cityAllList.value = cityList.flat() as unknown as TreeChildModel[];
    const currentCity = cityAllList.value.find((item: TreeChildModel) => item.tgCode === city.id) as unknown as TreeChildModel;
    if (!!currentCity) {
        formData.city = [currentCity.name];
        formData.cityCodeList = [currentCity.id];
        formData.checkedCityData = [currentCity];
        checkedData.value = [currentCity];
        citytxt.value = currentCity.name;
    }

});
onActivated(() => {
    checkedData.value = [];
});
const handleClick = (val: Tag[], index: number) => {
    if (index || index === 0) {
        form[index] = val;
    } else if (val[0].label === '按省市') {
        if (selecterType.value !== 1) {
            checkedData.value = [];
            formData.checkedCityData = [];
            formData.cityCodeList = [];
            citytxt.value = '';
        }
        selecterType.value = 1;
        cityList.value = provinceList.value;
        checkedData.value = formData.checkedCityData;
        showCityPicker.value = true;
        formData.isNationwide = false;
    } else if (val[0].label === '按城市级别') {
        if (selecterType.value !== 2) {
            checkedData.value = [];
            formData.checkedCityData = [];
            formData.cityCodeList = [];
            citytxt.value = '';
        }
        selecterType.value = 2;
        cityList.value = cityLevelList.value;
        checkedData.value = formData.checkedCityData;
        showCityPicker.value = true;
        formData.isNationwide = false;
    } else if (val[0].label === '全国') {
        selecterType.value = -1;
        formData.isNationwide = true;
        formData.city = ['全国'];
        formData.cityCodeList = cityAllList.value.map((item: TreeChildModel) => item.id);
        formData.checkedCityData = [];
        checkedData.value = [];
        citytxt.value = '全国';
    }
    console.log(checkedData.value);
    // console.log(formData.cityCodeList);
};


const currentCheckTagArrId = computed(() => {
    return currentCheckTag.value.map((item: TreeChildModel) => item.id);
});
const next = async () => {
    if (active.value === 'carefullyTag' && !currentCheckTag.value.length) {
        Toast.fail('请选择精选人群');
        return false;
    }
    if (active.value === 'customTag') {
        formData.customTag = [];
        Object.keys(form).forEach((key: string) => {
            const tag = form[key] as unknown as TreeChildModel[];
            formData.customTag.push(...tag);
        });
        if (formData.isNationwide) {
            formData.checkedCityData = cityAllList.value;
        }
        if (formData.cityCodeList.length === 0) {
            Toast.fail('请至少选择一个城市');
            return false;
        }
        if (!formData.preferenceIdList.length && !formData.isNationwide && !formData.customTag.length) {
            Toast.fail('请选择自定义标签');
            return false;
        }
    }
    formData.customKeyTag = form;
    if (active.value === 'customTag') {
        formData.currentCheckObjTag = [];
        store.commit('app/setSelectByTag', formData);
    }
    if (active.value === 'carefullyTag') {
        const carefullyFormData = {
            city: [],
            cityCodeList: [],
            checkedCityData: [],
            preference: [],
            preferenceIdList: [],
            customKeyTag: [],
            customTag: [],
            checkedPreferenceData: [],
            isNationwide: true,
            currentCheckObjTag: [] as Array<object>
        };
        carefullyFormData.currentCheckObjTag = currentCheckTag.value as Array<object>;
        store.commit('app/setSelectByTag', carefullyFormData);
    }
    await router.push({
        name: 'selectByTagMap',
        query: {
            isFromForgetting: 1
        }
    });

};

const pickTime = () => {
    selecterType.value = 3;
    cityList.value = industryList.value;
    showCityPicker.value = true;
    checkedData.value = formData.checkedPreferenceData;
};
const onCheckPerson = (item: TreeChildModel) => {
    const index = currentCheckTag.value.findIndex((checkItem: TreeChildModel) => item.id === checkItem.id);
    if (index === -1) {
        currentCheckTag.value.push(item);
    } else {
        currentCheckTag.value.splice(index, 1);
    }
    // Object.assign(currentCheckTag,item);
};
const formatCity = (arr: string[]) => {
    const len = arr.length;
    if (len > 4) {
        const str = arr.slice(0, 4).join('、');
        return `${str}等${len}个城市`;
    }
    return arr.slice(0, 4).join('、');


};
const formatPreference = (arr: string[]) => {
    const len = arr.length;
    const str = arr.slice(0, 1).join('、');
    return `${str}等${len}个偏好`;
};
const onCityConfirm = (value: ReturnData) => {
    console.log(value);
    if (selecterType.value === 3) {
        preference.value = formatPreference(value.nameList);
        formData.preference = value.nameList;
        formData.preferenceIdList = value.selected;
        formData.checkedPreferenceData = value.checkedData;

    } else {
        citytxt.value = formatCity(value.nameList);
        formData.city = value.nameList;
        citytxt.value = formatCity(formData.city);
        formData.cityCodeList = value.selected;
        formData.checkedCityData = value.checkedData;
        formData.isNationwide = false;
    }
    // checkedData.value =value.checkedData;


};


</script>

<style lang="scss" scoped>
.page {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    height: 100vh;
    background: #f4f4f4;
}

.card-info {
    flex: 1;
    overflow: auto;
    padding: 12px;
}

.card {
    box-sizing: border-box;
    padding: 12px 12px 2px;
    background: #ffffff;
    border-radius: 10px;
    margin-bottom: 52px;

    .tag {
        padding-top: 12px;
    }
}

.title {
    color: #333333;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    margin-top: 4px;
}

.title-sm {
    color: #333333;
    font-size: 14px;
    font-weight: 600;
    margin-top: 4px;
}

.city-label {
    color: #848484;
    margin-bottom: 24px;

    .city-sel {
        color: #333333;
    }
}

.van-cell {
    padding: 15px 0;
    align-items: center;
}

.icon {
    width: 12px;
    height: 12px;
}

:deep([class~="van-cell__title"]) {
    color: #5b5b5b;
}

:deep([class~="van-cell__value"]) {
    color: #333333;
    flex: 2;
}

:deep([class~="van-button"]) {
    background-color: #e60044;
    border: 0;
    border-radius: 6px;
    height: 38px;
}

// ::v-deep {
//     [class~="van-tabs__wrap"] {
//         padding-bottom: 10px;
//         border-bottom: 0.5px solid #f0f0f0;
//     }
// }
.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 6px 12px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0 -2px 4px 0 #ebebeb80;
    z-index: 1;
}

.person-list {
    background: #fff;
    padding-top: 12px;

    .person-item {
        display: flex;
        padding: 12px;
        background: #fff;
        border: 1px solid #eeeeee;
        border-radius: 10px;
        margin-bottom: 10px;
        align-items: center;
        position: relative;

        img {
            width: 48px;
            height: 48px;
        }

        .person-detail {
            font-size: 14px;
            color: #333333;
            margin-left: 15px;

            h4 {
                font-weight: bold;
            }

            p {
                margin-top: 10px;
            }
        }

        .check {
            width: 22px;
            height: 22px;
            position: absolute;
            right: -1px;
            bottom: -1px;
        }
    }

    .on {
        border: 1px solid #e60044;
    }
}

</style>
